import axios from 'axios';
import qs from 'qs';
axios.defaults.timeout = 10000;
// axios.defaults.baseURL = '/api';
//设置全局的请求次数，请求的间隙
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;

//http request 拦截器
axios.interceptors.request.use(
    config => {

        xmview.showLoading('请求数据中..')
            // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
            // config.data = JSON.stringify(config.data);
            // config.headers = {
            //     'Content-Type': 'application/x-www-form-urlencoded'
            // }
            // if(token){
            //   config.params = {'token':token}
            // }
        if (config.method == "post") {
            config.data = qs.stringify(config.data);
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        }
        return config;
    },
    error => {
        return Promise.reject(err);
    }
);


//http response 拦截器
axios.interceptors.response.use(
    response => {
        // if (response.data.errCode == 2) {
        //       router.push({
        //         path:"/login",
        //         querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
        //       })
        // }
        // if (response.status === 200 && response.data.code === 200) {
        if (response.status === 200) {
            xmview.hideLoading()
            return response;
        } else {
            xmview.hideLoading()
            debugger
            if (response.data.msg) {
                xmview.showAlert('', response.data.msg, '', () => {})
            }
        }

    },
    err => {
        xmview.hideLoading()
        xmview.showToast(err.message)
            // return Promise.reject(err)

        // 下面是 错误后连续四次请求
        var config = err.config;
        // If config does not exist or the retry option is not set, reject
        if (!config || !config.retry) return Promise.reject(err);

        // Set the variable for keeping track of the retry count
        config.__retryCount = config.__retryCount || 0;

        // Check if we've maxed out the total number of retries
        if (config.__retryCount >= config.retry) {
            // Reject with the error
            return Promise.reject(err);
        }

        // Increase the retry count
        config.__retryCount += 1;

        // Create new promise to handle exponential backoff
        var backoff = new Promise(function(resolve) {
            setTimeout(function() {
                resolve();
            }, config.retryDelay || 1);
        });

        // Return the promise in which recalls axios to retry the request
        return backoff.then(function() {
            return axios(config);
        });
    }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: params
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}